package com.ib.review.base.utils;

import com.ib.review.pojo.bo.TableCell;
import com.ib.review.pojo.bo.TableData;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ExcelExporter {
    public static byte[] exportTablesToExcel(List<TableData> tables) throws IOException {
        try (Workbook workbook = new XSSFWorkbook()) {
            if (tables == null || tables.isEmpty()) {
                return new byte[0];
            }

            // 用于跟踪每种列数对应的sheet序号
            Map<Integer, Integer> sheetSequenceMap = new HashMap<>();

            for (TableData table : tables) {
                // Calculate column count for current table
                int tableColumnCount = 0;
                if (table.getTableData() != null && !table.getTableData().isEmpty()) {
                    tableColumnCount = table.getTableData().stream()
                            .mapToInt(List::size)
                            .max()
                            .orElse(0);
                }

                // Skip empty tables
                if (tableColumnCount == 0) continue;

                // Create sheet name
                String baseSheetName = "包含" + tableColumnCount + "列表格数据";

                // Get or initialize sequence number for this column count
                int sequence = sheetSequenceMap.getOrDefault(tableColumnCount, 1);
                String sheetName = baseSheetName;

                // Add sequence number if needed
                if (sequence > 1) {
                    sheetName = baseSheetName + "-" + sequence;
                }

                // Ensure sheet name is unique (in case of conflicts with other column counts)
                int uniqueSequence = 1;
                String finalSheetName = sheetName;
                while (workbook.getSheet(finalSheetName) != null) {
                    finalSheetName = sheetName + "-" + (uniqueSequence++);
                }

                // Create new sheet
                Sheet currentSheet = workbook.createSheet(finalSheetName);

                // Update sequence for next table with same column count
                sheetSequenceMap.put(tableColumnCount, sequence + 1);

                // Process the table in current sheet
                processTable(workbook, currentSheet, table);
            }

            // Write to byte array
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return outputStream.toByteArray();
        }
    }

    private static void processTable(Workbook workbook, Sheet sheet, TableData table) {
        List<List<TableCell>> tableData = table.getTableData();
        if (tableData == null || tableData.isEmpty()) {
            return;
        }
        int startRowNum = 0;

        // 1. 创建基础样式（带边框）
        CellStyle baseStyle = workbook.createCellStyle();
        baseStyle.setAlignment(HorizontalAlignment.CENTER);
        baseStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置边框
        baseStyle.setBorderTop(BorderStyle.THIN);
        baseStyle.setBorderBottom(BorderStyle.THIN);
        baseStyle.setBorderLeft(BorderStyle.THIN);
        baseStyle.setBorderRight(BorderStyle.THIN);
        // 可选：设置边框颜色
        baseStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
        baseStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        baseStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        baseStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());

        // 2. 预处理数据（同之前）
        List<List<TableCell>> processedData = tableData.stream()
                .map(row -> row.stream()
                        .map(cell -> "EMPTY".equals(cell.getTagName())
                                ? new TableCell("", 1, 1, "TD")
                                : cell)
                        .collect(Collectors.toList()))
                .toList();

        // 3. 计算最大列数
        int maxColumns = processedData.stream()
                .mapToInt(List::size)
                .max()
                .orElse(0);

        // 4. 创建所有行并应用边框
        for (int i = 0; i < processedData.size(); i++) {
            Row row = sheet.createRow(startRowNum + i);
            // 可选：为整行设置默认高度
            row.setHeightInPoints(20);
        }

        // 5. 处理合并单元格（同之前）
        for (int rowIdx = 0; rowIdx < processedData.size(); rowIdx++) {
            List<TableCell> row = processedData.get(rowIdx);
            for (int colIdx = 0; colIdx < row.size(); colIdx++) {
                TableCell cell = row.get(colIdx);
                if (cell.getColSpan() > 1 || cell.getRowSpan() > 1) {
                    CellRangeAddress region = new CellRangeAddress(
                            startRowNum + rowIdx,
                            startRowNum + rowIdx + cell.getRowSpan() - 1,
                            colIdx,
                            colIdx + cell.getColSpan() - 1
                    );
                    sheet.addMergedRegion(region);

                    // 为合并区域设置边框
                    setMergedRegionBorders(workbook, sheet, region);
                }
            }
        }

        // 6. 填充单元格值并应用样式
        for (int rowIdx = 0; rowIdx < processedData.size(); rowIdx++) {
            Row excelRow = sheet.getRow(startRowNum + rowIdx);
            List<TableCell> row = processedData.get(rowIdx);

            for (int colIdx = 0; colIdx < row.size(); colIdx++) {
                TableCell cell = row.get(colIdx);
                Cell excelCell = excelRow.createCell(colIdx);
                excelCell.setCellValue(cell.getValue());
                excelCell.setCellStyle(baseStyle); // 应用带边框的样式
            }
        }

        // 7. 设置列宽（同之前）
        for (int i = 0; i < maxColumns; i++) {
            sheet.setColumnWidth(i, 3000);
        }

    }

    // 为合并区域设置边框的辅助方法
    private static void setMergedRegionBorders(Workbook workbook, Sheet sheet, CellRangeAddress region) {
        for (int r = region.getFirstRow(); r <= region.getLastRow(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) continue;

            for (int c = region.getFirstColumn(); c <= region.getLastColumn(); c++) {
                Cell cell = row.getCell(c);
                if (cell == null) continue;

                // 只设置外围边框
                CellStyle style = workbook.createCellStyle();
                style.cloneStyleFrom(cell.getCellStyle());
                if (r == region.getFirstRow()) style.setBorderTop(BorderStyle.THIN);
                if (r == region.getLastRow()) style.setBorderBottom(BorderStyle.THIN);
                if (c == region.getFirstColumn()) style.setBorderLeft(BorderStyle.THIN);
                if (c == region.getLastColumn()) style.setBorderRight(BorderStyle.THIN);
                cell.setCellStyle(style);
            }
        }
    }
}